#!/bin/bash

function helpMessage() {
    echo "SYNOPSIS"
    echo "    ./package.sh -n <module> -v <version> -p <platform> -t [Debug | Release]"
    echo "OPTIONS"
    echo "    -h: show help for package.sh"
    echo "    -n: specified module name, like libev, upgrade ..."
    echo "    -p: specified platform, like S3C2440, LC1881, SM8475 ..."
    echo "    -v: specified module version, for example V1.0.2 or V1.2.1.2"
    echo "    -t: specified build type, alternative Debug and Release"
}

while getopts "n:p:v:t:" opt; do
    case $opt in
    n)
        MODULE_NAME="$OPTARG"
        ;;
    v)
        MODULE_VER="$OPTARG"
        ;;
    p)
        MODULE_PLAT="$OPTARG"
        ;;
    t)
        if [ "$OPTARG" != "Debug" ] && [ "$OPTARG" != "Release" ]; then
            echo "build type only alternative debug and release"
            exit 1
        fi
        BUILD_TYPE="$OPTARG"
        ;;
    h)
        helpMessage
        exit 1
        ;;
    ?)
        echo "    There is unrecognized parameter!"
        helpMessage
        exit 1
        ;;
    esac
done

if [ ! -n "$MODULE_NAME" ]; then
    echo "Please specified module name: -m <module>"
    echo "Try './package.sh -h' for more information."
    exit 1
fi
if [ ! -n "$MODULE_VER" ]; then
    echo "Please specified module version: -v <version>"
    echo "Try './package.sh -h' for more information."
    exit 1
fi
if [ ! -n "$MODULE_PLAT" ]; then
    echo "Please specified platform: -p <platform>"
    echo "Try './package.sh -h' for more information."
    exit 1
fi
if [ ! -n "$BUILD_TYPE" ]; then
    BUILD_TYPE="Release"
fi
if [ ! -d "$BUILD_TYPE" ]; then
    echo "$BUILD_TYPE is not exist!"
    exit 1
fi

CURDIR=$(cd $(dirname $0); pwd)
timeStamp=`date "+%Y%m%d%H%M%S"`
packageName=$MODULE_NAME-$MODULE_VER-$timeStamp.$MODULE_PLAT.$BUILD_TYPE.tar.gz

mkdir package -p
mv $BUILD_TYPE $MODULE_NAME
tar -czvf package/$packageName $MODULE_NAME
if [ $? -eq 0 ]; then
    echo "package $packageName success"
else
    echo "package $packageName failure"
fi
mv $MODULE_NAME $BUILD_TYPE

